package org.bjf.modules.sys.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bjf.cache.CacheNameConfig.RedisCacheEnum.Names;
import org.bjf.modules.core.service.BaseService;
import org.bjf.modules.sys.bean.SysUser;
import org.bjf.modules.sys.bean.SysUserRole;
import org.bjf.modules.sys.mapper.SysUserMapper;
import org.bjf.modules.sys.query.SysUserQuery;
import org.bjf.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author bjf
 * @date 2017/11/27
 */
@Service
@Slf4j
public class SysUserService extends BaseService<SysUserMapper, SysUser, SysUserQuery> {

  @Autowired
  private SysUserRoleService userRoleService;
  @Autowired
  private RedisUtil redis;

  @Override
  protected EntityWrapper<SysUser> buildQuery(SysUserQuery q) {
    if (q == null) {
      return null;
    }
    EntityWrapper<SysUser> ew = new EntityWrapper<>();
    ew.eq(StringUtils.isNotBlank(q.getUsername()), "username", q.getUsername());
    ew.eq(StringUtils.isNotBlank(q.getPhone()), "phone", q.getPhone());
    return ew;
  }

  /**
   * 给用户分配角色
   */
  @CacheEvict(value = Names.SYS, key = "'live:role:listByUser:' + #sysUserId")
  @Transactional(rollbackFor = Exception.class)
  public void updateRole(long sysUserId, String roleIds) {
    String[] split = StringUtils.split(roleIds, ",");
    List<SysUserRole> list = new ArrayList<>(split.length);
    for (String roleId : split) {
      SysUserRole userRole = new SysUserRole();
      userRole.setSysUserId(sysUserId);
      userRole.setSysRoleId(Long.valueOf(roleId));

      list.add(userRole);
    }

    //===1、先删除用户原有角色
    userRoleService.delete(new EntityWrapper<SysUserRole>().eq("sys_user_id", sysUserId));

    //===2、批量新增用户角色
    userRoleService.insertBatch(list);

    clearUserCache();

  }

  /**
   * 删除用户权限
   */
  @Async
  public void clearUserCache() {
    //===1.删除角色权限缓存
    Set<String> keys = redis.keys("live:acl:listRolePermission:*");
    for (String key : keys) {
      redis.delete(key);
    }

    //===2.清除用户权限缓存
    Set<String> userKeys = redis.keys("live:acl:hasControllerPermission:*");
    for (String key : userKeys) {
      redis.delete(key);
    }

    //===4.清除用户菜单缓存
    Set<String> menuKeys = redis.keys("live:menu:listByUser:*");
    for (String key : menuKeys) {
      redis.delete(key);
    }
  }

}
